<script setup>
import { ref, defineProps, computed, defineEmits, watchEffect } from 'vue'
const props = defineProps(['time', 'id'])
const emit = defineEmits(['downChange'])
import { useI18n } from 'vue-i18n'

const {t} = useI18n()
// 获取当前时间戳
const currentTime = ref(Date.now())
const date = new Date(props.time).getTime()
// 获取两者时间戳差值
const timeRemaining = ref(date - currentTime.value)
// 计算属性 计算天、小时、分钟、秒
const days = computed(() =>
  Math.floor(timeRemaining.value / (1000 * 60 * 60 * 24)),
)
const hours = computed(() =>
  Math.floor(
    (timeRemaining.value % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60),
  ),
)
const minutes = computed(() =>
  Math.floor((timeRemaining.value % (1000 * 60 * 60)) / (1000 * 60)),
)
const seconds = computed(() =>
  Math.floor((timeRemaining.value % (1000 * 60)) / 1000),
)
// 依赖的数据变化，将其导出
const formattedTime = computed(() => {
  return `${days.value < 10 ? '0' + days.value : days.value}${ t('menu.days') } ${hours.value < 10 ? '0' + hours.value : hours.value
    }${t('menu.hours')} ${minutes.value < 10 ? '0' + minutes.value : minutes.value}${t('menu.minutes')} ${seconds.value < 10 ? '0' + seconds.value : seconds.value
    }${t('menu.seconds')}`
})
// 倒计时函数
const intervalId = ref(null)
const startCountdown = () => {
  intervalId.value && clearTimeout(intervalId.value)
  intervalId.value = setTimeout(() => {
    currentTime.value = Date.now()
    timeRemaining.value = date - currentTime.value
    startCountdown()
  }, 1000)
}
// 前提条件, 不能为负值
if(timeRemaining.value > 1000) {
  startCountdown()
}
const isTimeShow = ref(true);
watchEffect(() => {
  if (timeRemaining.value <= 1000) {
    console.log('清除定时器')
    clearTimeout(intervalId.value)
    isTimeShow.value = false
    emit('downChange', props.id)
  }
})
</script>
<template>
  <span v-if="isTimeShow" style="display: flex;align-items: center;">{{ formattedTime }} {{$t('menu.postCancellation')}}</span>
  <span v-else>{{ $t('menu.status') }}</span>
</template>